﻿using System;
using log4net;

namespace AppServer.Core
{
    /// <summary>
    /// 抽象的AppSession基类
    /// </summary>
    public abstract class AbstractAppSession:IAppSession
    {
        protected ILog logger = Logger.GetLogger("AppSession");

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="token">UserToken</param>
        public AbstractAppSession(object token)
        {
            this.Id = Guid.NewGuid();
            this.UserToken = token;
        }

        event EventHandler m_Released;
        /// <summary>
        /// 释放事件
        /// </summary>
        public event EventHandler Released
        {
            add
            {
                m_Released += value;
            }
            remove
            {
                m_Released -= value;
            }
        }

        /// <summary>
        /// 释放
        /// </summary>
        protected virtual void OnRelease()
        {
            if (m_Released != null)
            {
                m_Released(this, new EventArgs());
            }
        }

        /// <summary>
        /// SessionId
        /// </summary>
        public Guid Id
        {
            get;
            protected set;
        }

        /// <summary>
        /// Session UserToken
        /// </summary>
        public object UserToken
        {
            get;
            protected set;
        }

        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>发送成功或失败</returns>
        public abstract bool Send(ICommand command);
       
        /// <summary>
        /// 释放
        /// </summary>
        public virtual void Release()
        {
            OnRelease();
        }

        /// <summary>
        /// ToString
        /// </summary>
        /// <returns>UserToken.ToString</returns>
        public override string ToString()
        {
            return this.UserToken.ToString();
        }
    }
}
